package com.flyu.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.flyu.pojo.Bill;
import com.flyu.pojo.Provider;
import com.flyu.pojo.User;
import com.flyu.service.bill.BillServiceImpl;
import com.flyu.service.provider.ProviderServiceImpl;
import com.flyu.util.Constants;
import com.flyu.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query") && method != null){
            this.query(req, resp);
        } else if (method.equals("delbill") && method != null){
            this.delBill(req, resp);
        } else if (method.equals("view") && method != null){
            this.getBillById(req, resp, "billview.jsp");
        } else if (method.equals("modify") && method != null){
            this.getBillById(req, resp, "billmodify.jsp");
        } else if (method.equals("getproviderlist") && method != null){
            this.getproviderlist(req, resp);
        } else if (method.equals("modifysave") && method != null){
            this.modifySave(req, resp);
        } else if (method.equals("add") && method != null){
            this.addBill(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 查询订单记录
    public void query(HttpServletRequest req, HttpServletResponse resp){
        // 从前端获取参数
        String queryProductName = req.getParameter("queryProductName");
        String queryProviderId = req.getParameter("queryProviderId");
        String queryIsPayment = req.getParameter("queryIsPayment");
        int providerId = 0;
        int isPayment = 0;

        BillServiceImpl billService = new BillServiceImpl();
        // 分页
        String pageIndex = req.getParameter("pageIndex");
        int pageSize = 5;
        int currentPageNo = 1;
        int totalCount = billService.getBillCount(queryProductName, providerId, isPayment);
        // 总页数
        int totalPageCount = ((int) (totalCount/pageSize))+1;
        // 控制首尾页
        if (currentPageNo < 1){
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        if (pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }


        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        if (queryProductName==null){
            queryProductName = "";
        }
        if (queryProviderId!=null && !queryProviderId.equals("")){
            providerId = Integer.parseInt(queryProviderId);
        }
        if (queryIsPayment != null && !queryIsPayment.equals("")){
            isPayment = Integer.parseInt(queryIsPayment);
        }
        // 展示订单
        List<Bill> billList = billService.getBillList(queryProductName, providerId, isPayment, currentPageNo, pageSize);
        req.setAttribute("billList", billList);
        // 选择框展示供应商
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        List<Provider> providerList = providerService.getProviderList();
        req.setAttribute("providerList", providerList);
        // 显示页数
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        // 让检索条件保持显示
        req.setAttribute("queryProductName", queryProductName);
        req.setAttribute("queryProviderId", queryProviderId);
        req.setAttribute("queryIsPayment", queryIsPayment);

        try {
            req.getRequestDispatcher("billlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 删除订单记录
    public void delBill(HttpServletRequest req, HttpServletResponse resp){
        // 从前端获取billId
        int billid = Integer.parseInt(req.getParameter("billid"));
        // 结果集
        Map<String, String> resultMap = new HashMap<String, String>();
        if (billid < 0) {   // 不存在小于0的billid，还可以去数据库里查一遍，这里偷个懒
            resultMap.put("delResult", "notexist");
        } else {
            BillServiceImpl billService = new BillServiceImpl();
            if (billService.delBillById(billid)){   // 删除成功
                resultMap.put("delResult", "true");
            }else {
                resultMap.put("delResult", "false");
            }
        }
        // 将resultMap转为Json后传给前端
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }
    // 查看
    public void getBillById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        // 从前端获取billId
        int billid = Integer.parseInt(req.getParameter("billid"));
        BillServiceImpl billService = new BillServiceImpl();
        Bill bill = billService.getBillById(billid);
        req.setAttribute("bill", bill);
        req.getRequestDispatcher(url).forward(req, resp);
    }
    // 获取供应商列表
    public void getproviderlist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ProviderServiceImpl providerService = new ProviderServiceImpl();
        List<Provider> providerList = providerService.getProviderList();
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(providerList));
        writer.flush();
        writer.close();
    }
    // 保存修改
    public void modifySave(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");
        String id = req.getParameter("id");
        Object[] params = {billCode, productName, productUnit, productCount, totalPrice, providerId, isPayment, id};
        BillServiceImpl billService = new BillServiceImpl();
        boolean flag = billService.modifySave(params);
        if (flag){  // 修改并保存成功
            resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query");
        } else {
            req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
        }
    }
    // 添加订单
    public void addBill(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String isPayment = req.getParameter("isPayment");
        String providerId = req.getParameter("providerId");

        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        User currentUser = (User) o;    // 当前登录的用户
        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount));
        bill.setTotalPrice(new BigDecimal(totalPrice));
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setCreationDate(new Date());
        bill.setCreatedBy(((User) o).getId());
        BillServiceImpl billService = new BillServiceImpl();
        boolean flag = billService.addBill(bill);
        if (flag){
            resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query");
        }else {
            req.getRequestDispatcher("billadd.jsp").forward(req, resp);
        }
    }
}
